﻿/*
 * 文件名称：
 * 程序员：wangyun
 * 创建时间：2008/06/03
 * 
 * 功能说明：模板功能模块导入导出
 * 
 * 修改人员：
 * 
 * 修改日期：
 * 
 * 修改记录：
 */

using System;
using System.Data;
using System.Web;
using System.Xml;
using System.Text;
using Whir.Common.WebHelper;
using Whir.Common;
using System.IO;

public class ModelTemplateHelper
{
    #region 导入
    /// <summary>
    /// 导入功能模块模板
    /// </summary>
    /// <param name="templateName">模板名称</param>
    /// <param name="modelMark">功能模块标识</param>
    /// <param name="modelName">功能模块名称</param>
    /// <param name="modelDesc">功能模块描述</param>
    /// <param name="modelIcon">图标文件</param>
    /// <param name="tableName">表名</param>
    /// <param name="isUse">是否启用</param>
    public static bool Import(string templateName, string modelMark, string modelName, string modelDesc, string modelIcon, string tableName, bool isUse)
    {
        Whir.Model.Whir_FieldText fieldTextModel = new Whir.Model.Whir_FieldText();
        Whir.BLL.Whir_FieldText fieldTextBll = new Whir.BLL.Whir_FieldText();

        Whir.Model.Whir_FieldEditor fieldEditorModel = new Whir.Model.Whir_FieldEditor();
        Whir.BLL.Whir_FieldEditor fieldEditorBLL = new Whir.BLL.Whir_FieldEditor();

        Whir.Model.Whir_FieldOption fieldOptionModel = new Whir.Model.Whir_FieldOption();
        Whir.BLL.Whir_FieldOption fieldOptionBLL = new Whir.BLL.Whir_FieldOption();

        Whir.Model.Whir_FieldUpload fieldUploadModel = new Whir.Model.Whir_FieldUpload();
        Whir.BLL.Whir_FieldUpload fieldUploadBLL = new Whir.BLL.Whir_FieldUpload();

        Whir.Model.Whir_FieldDateText fieldDateTextModel = new Whir.Model.Whir_FieldDateText();
        Whir.BLL.Whir_FieldDateText fieldDateTextBLL = new Whir.BLL.Whir_FieldDateText();

        Whir.Model.Whir_FieldCheckBox fieldCheckBoxModel = new Whir.Model.Whir_FieldCheckBox();
        Whir.BLL.Whir_FieldCheckBox fieldCheckBoxBLL = new Whir.BLL.Whir_FieldCheckBox();

        bool flag = true;

        #region 创建表
        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        Whir.BLL.Whir_Model bll = new Whir.BLL.Whir_Model();

        model.moduleMark = modelMark;
        model.modelName = modelName;
        model.modelDesc = modelDesc;
        model.modelIcon = modelIcon;
        model.tableName = tableName;
        model.isUse = isUse;
        int newModelID = bll.Add(model);    //添加功能模块

        Whir.Common.SqlDMOHelper dmo = new Whir.Common.SqlDMOHelper();
        flag = dmo.CreateTable(tableName); //创建表
        #endregion

        if (flag)
        {
            string filePath = HttpContext.Current.Server.MapPath("~/Temp/ModelTemplates/");
            XmlTextReader r = new XmlTextReader(filePath + templateName);

            Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();
            Whir.Model.Whir_Field fieldModel = new Whir.Model.Whir_Field();
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.LocalName == "Field")
                {
                    #region 添加字段
                    int modelID = newModelID;
                    fieldModel.modelID = modelID;
                    fieldModel.fieldName = r.GetAttribute("fieldName");
                    fieldModel.alias = r.GetAttribute("alias");
                    fieldModel.rating = Convert.ToBoolean(r.GetAttribute("rating"));
                    fieldModel.fieldTip = r.GetAttribute("fieldTip");
                    fieldModel.fieldDesc = r.GetAttribute("fieldDesc");
                    fieldModel.isRequired = Convert.ToBoolean(r.GetAttribute("isRequired"));
                    fieldModel.isUse = Convert.ToBoolean(r.GetAttribute("isUse"));
                    fieldModel.sort = Convert.ToInt32(r.GetAttribute("sort"));
                    fieldModel.fieldType = Convert.ToInt32(r.GetAttribute("fieldType"));
                    fieldModel.typeName = r.GetAttribute("typeName");
                    fieldModel.typeLength = Convert.ToInt32(r.GetAttribute("typeLength"));
                    fieldModel.isAllowNull = Convert.ToBoolean(r.GetAttribute("isAllowNull"));
                    fieldModel.banUserIDs = "";
                    fieldModel.banRoleIDs = "";
                    fieldModel.isValidate = true;
                    fieldModel.validateType = 0;
                    fieldModel.validateMsg = "";
                    fieldModel.validateTo = "";
                    fieldModel.createUserID = 0;
                    fieldModel.updateUserID = 0;
                    fieldModel.isIdentity = false;
                    fieldModel.identityIncrement = 0;
                    fieldModel.identitySeed = 0;
                    fieldModel.defaultValue = "";
                    int newFieldID = fieldBll.Add(fieldModel);
                    #endregion

                    #region 添加字段到数据库实际表单中
                    dmo = new Whir.Common.SqlDMOHelper();

                    SQLDMO.Column Col1 = new SQLDMO.Column();
                    Col1.Name = fieldModel.fieldName;
                    Col1.Datatype = fieldModel.typeName;
                    Col1.Length = fieldModel.typeLength;
                    Col1.AllowNulls = true;
                    Col1.Default = fieldModel.defaultValue;

                    flag = dmo.AddColumnInTable(tableName, Col1);
                    #endregion

                    #region 添加字段类型
                    switch ((FieldType)fieldModel.fieldType)
                    {
                        case FieldType.None:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = "";
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 1; //单行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.TextType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = r.GetAttribute("textWidth");
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 1; //单行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.MultipleTextType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = r.GetAttribute("textWidth");
                            fieldTextModel.textHeight = r.GetAttribute("textHeight");//0为默认
                            fieldTextModel.textType = 2; //多行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.MultipleHtmlTextType:
                            fieldEditorModel.fieldID = newFieldID;
                            fieldEditorModel.editorMode = Convert.ToInt32(r.GetAttribute("editorMode"));
                            fieldEditorModel.textWidth = r.GetAttribute("textWidth");
                            fieldEditorModel.textHeight = r.GetAttribute("textHeight");
                            fieldEditorModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldEditorModel.editorType = Convert.ToInt32(r.GetAttribute("editorType"));
                            fieldEditorBLL.Add(fieldEditorModel);
                            break;
                        case FieldType.ListBoxType:
                            fieldOptionModel.fieldID = newFieldID;
                            fieldOptionModel.optionType = Convert.ToInt32(r.GetAttribute("optionType"));   //1、下拉列表框2、单选按钮组3、多选按钮组
                            fieldOptionModel.bindValue = r.GetAttribute("bindValue");
                            fieldOptionModel.cellNum = Convert.ToInt32(r.GetAttribute("cellNum"));
                            fieldOptionModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldOptionModel.bindType = 1;
                            fieldOptionModel.sql = "";
                            fieldOptionModel.sqlChild = "";
                            fieldOptionModel.height = "";
                            fieldOptionModel.width = "";
                            fieldOptionModel.firthOption = "";
                            fieldOptionModel.onChange = "";
                            fieldOptionModel.valueField = "";
                            fieldOptionModel.textField = "";
                            fieldOptionBLL.Add(fieldOptionModel);
                            break;
                        case FieldType.NumberType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = "";
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 1; //单行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.MoneyType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = "";
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 1; //单行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.DateTimeType:
                            fieldDateTextModel.fieldID = newFieldID;
                            fieldDateTextModel.dateFormat = Convert.ToInt32(r.GetAttribute("dataFormat"));
                            fieldDateTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldDateTextModel.width = r.GetAttribute("width");
                            fieldDateTextBLL.Add(fieldDateTextModel);
                            break;
                        case FieldType.LinkType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = r.GetAttribute("textWidth");
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 1; //单行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.BoolType:
                            fieldOptionModel.fieldID = newFieldID;
                            fieldOptionModel.optionType = 2;    //1、下拉列表框2、单选按钮组3、多选按钮组
                            fieldOptionModel.bindValue = "是|否";
                            fieldOptionModel.cellNum = 0;
                            fieldOptionModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldOptionModel.bindType = 1;
                            fieldOptionModel.sql = "";
                            fieldOptionModel.sqlChild = "";
                            fieldOptionModel.height = "";
                            fieldOptionModel.width = "";
                            fieldOptionModel.firthOption = "";
                            fieldOptionModel.onChange = "";
                            fieldOptionModel.valueField = "";
                            fieldOptionModel.textField = "";
                            fieldOptionBLL.Add(fieldOptionModel);
                            break;
                        case FieldType.PictureType:
                            fieldUploadModel.fieldID = newFieldID;
                            fieldUploadModel.maxSize = Convert.ToInt32(r.GetAttribute("maxSize"));
                            fieldUploadModel.allowType = r.GetAttribute("allowType");
                            fieldUploadModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldUploadBLL.Add(fieldUploadModel);
                            break;
                        case FieldType.FileType:
                            fieldUploadModel.fieldID = newFieldID;
                            fieldUploadModel.maxSize = Convert.ToInt32(r.GetAttribute("maxSize"));
                            fieldUploadModel.allowType = r.GetAttribute("allowType");
                            fieldUploadModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldUploadBLL.Add(fieldUploadModel);
                            break;
                        case FieldType.ColorType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = "";
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 1; //单行文本
                            fieldTextModel.defaultValue = r.GetAttribute("defaultValue");
                            fieldTextBll.Add(fieldTextModel);
                            break;
                        case FieldType.PassWordType:
                            fieldTextModel.fieldID = newFieldID;
                            fieldTextModel.textWidth = r.GetAttribute("textWidth");
                            fieldTextModel.textHeight = "";//0为默认
                            fieldTextModel.textType = 3; //单行文本
                            fieldTextModel.defaultValue = "";// TxtTextDefaultValue.Text.Trim();
                            fieldTextBll.Add(fieldTextModel);
                            break;
                    }
                    #endregion
                }
            }
            r.Close();
        }

        return flag;
    }
    #endregion

    #region 导出
    /// <summary>
    /// 导出功能模块模板
    /// </summary>
    /// <param name="modelID">功能模块 ID</param>
    /// <param name="fileName">导出文件名</param>
    public static void Export(int modelID, string fileName)
    {
        Whir.BLL.Whir_Model modelBll = new Whir.BLL.Whir_Model();
        Whir.Model.Whir_Model modelModel = new Whir.Model.Whir_Model();

        Whir.BLL.Whir_FieldText fieldTextBll = new Whir.BLL.Whir_FieldText();
        Whir.Model.Whir_FieldText fieldTextModel = new Whir.Model.Whir_FieldText();

        Whir.BLL.Whir_FieldEditor fieldEditorBLL = new Whir.BLL.Whir_FieldEditor();
        Whir.Model.Whir_FieldEditor fieldEditorModel = new Whir.Model.Whir_FieldEditor();

        Whir.BLL.Whir_FieldOption fieldOptionBLL = new Whir.BLL.Whir_FieldOption();
        Whir.Model.Whir_FieldOption fieldOptionModel = new Whir.Model.Whir_FieldOption();

        Whir.BLL.Whir_FieldUpload fieldUploadBLL = new Whir.BLL.Whir_FieldUpload();
        Whir.Model.Whir_FieldUpload fieldUploadModel = new Whir.Model.Whir_FieldUpload();

        Whir.BLL.Whir_FieldDateText fieldDateTextBLL = new Whir.BLL.Whir_FieldDateText();
        Whir.Model.Whir_FieldDateText fieldDateTextModel = new Whir.Model.Whir_FieldDateText();

        modelModel = modelBll.GetModel(modelID);
        if (modelModel != null)
        {
            string fileContentType = ".xml";
            string filePath = HttpContext.Current.Server.MapPath("~/Temp/ModelTemplates/");
            XmlTextWriter w = new XmlTextWriter(filePath + fileName + fileContentType, Encoding.UTF8);
            w.Formatting = Formatting.Indented;
            w.WriteStartDocument();

            w.WriteStartElement("Model");

            #region 功能模块信息
            w.WriteStartElement("ModelMark");
            w.WriteString(modelModel.moduleMark);
            w.WriteEndElement();

            w.WriteStartElement("ModelName");
            w.WriteString(modelModel.modelName);
            w.WriteEndElement();

            w.WriteStartElement("ModelDesc");
            w.WriteString(modelModel.modelDesc);
            w.WriteEndElement();

            w.WriteStartElement("ModelIcon");
            w.WriteString(modelModel.modelIcon);
            w.WriteEndElement();

            w.WriteStartElement("TableName");
            w.WriteString(modelModel.tableName);
            w.WriteEndElement();

            w.WriteStartElement("IsUse");
            w.WriteString(modelModel.isUse.ToString());
            w.WriteEndElement();
            #endregion

            #region 字段信息
            w.WriteStartElement("Fields");

            DataTable dt = new Whir.BLL.Whir_Field().GetList("ModelID=" + modelID).Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                w.WriteStartElement("Field");

                w.WriteAttributeString("fieldName", dr["fieldName"].ToString());
                w.WriteAttributeString("alias", dr["alias"].ToString());
                w.WriteAttributeString("rating", dr["rating"].ToString());
                w.WriteAttributeString("fieldTip", dr["fieldTip"].ToString());

                w.WriteAttributeString("fieldDesc", dr["fieldDesc"].ToString());
                w.WriteAttributeString("isRequired", dr["isRequired"].ToString());
                w.WriteAttributeString("isUse", dr["isUse"].ToString());
                w.WriteAttributeString("sort", dr["sort"].ToString());

                w.WriteAttributeString("fieldType", dr["fieldType"].ToString());
                w.WriteAttributeString("typeName", dr["typeName"].ToString());
                w.WriteAttributeString("typeLength", dr["typeLength"].ToString());
                w.WriteAttributeString("isAllowNull", dr["isAllowNull"].ToString());

                switch ((FieldType)int.Parse(dr["fieldType"].ToString()))
                {
                    case FieldType.None:
                    case FieldType.TextType:
                    case FieldType.MoneyType:
                    case FieldType.ColorType:
                    case FieldType.MultipleTextType:
                    case FieldType.NumberType:
                    case FieldType.LinkType:
                        fieldTextModel = fieldTextBll.GetModel(int.Parse(fieldTextBll.GetList("FieldID=" + dr["fieldID"].ToString()).Tables[0].Rows[0][0].ToString()));
                        w.WriteAttributeString("textWidth", fieldTextModel.textWidth);
                        w.WriteAttributeString("textHeight", fieldTextModel.textHeight);
                        w.WriteAttributeString("textType", fieldTextModel.textType.ToString());
                        w.WriteAttributeString("defaultValue", fieldTextModel.defaultValue);
                        break;
                    case FieldType.DateTimeType:
                        fieldDateTextModel = fieldDateTextBLL.GetModel(int.Parse(fieldDateTextBLL.GetList("FieldID=" + dr["fieldID"].ToString()).Tables[0].Rows[0][0].ToString()));
                        w.WriteAttributeString("dataFormat", fieldDateTextModel.dateFormat.ToString());
                        w.WriteAttributeString("width", fieldDateTextModel.width);
                        w.WriteAttributeString("defaultValue", fieldDateTextModel.defaultValue);
                        break;
                    case FieldType.BoolType:
                    case FieldType.ListBoxType:
                        fieldOptionModel = fieldOptionBLL.GetModel(int.Parse(fieldOptionBLL.GetList("FieldID=" + dr["fieldID"].ToString()).Tables[0].Rows[0][0].ToString()));
                        w.WriteAttributeString("optionType", fieldOptionModel.optionType.ToString());
                        w.WriteAttributeString("bindValue", fieldOptionModel.bindValue.ToString());
                        w.WriteAttributeString("cellNum", fieldOptionModel.cellNum.ToString());
                        w.WriteAttributeString("bindType", fieldOptionModel.bindType.ToString());
                        w.WriteAttributeString("defaultValue", fieldOptionModel.defaultValue);
                        break;
                    case FieldType.MultipleHtmlTextType:
                        fieldEditorModel = fieldEditorBLL.GetModel(int.Parse(fieldEditorBLL.GetList("FieldID=" + dr["fieldID"].ToString()).Tables[0].Rows[0][0].ToString()));
                        w.WriteAttributeString("editorMode", fieldEditorModel.editorMode.ToString());
                        w.WriteAttributeString("editorType", fieldEditorModel.editorType.ToString());
                        w.WriteAttributeString("textWidth", fieldEditorModel.textWidth);
                        w.WriteAttributeString("textHeight", fieldEditorModel.textHeight);
                        w.WriteAttributeString("defaultValue", fieldEditorModel.defaultValue);
                        break;
                    case FieldType.FileType:
                    case FieldType.PictureType:
                        fieldUploadModel = fieldUploadBLL.GetModel(int.Parse(fieldUploadBLL.GetList("FieldID=" + dr["fieldID"].ToString()).Tables[0].Rows[0][0].ToString()));
                        w.WriteAttributeString("maxSize", fieldUploadModel.maxSize.ToString());
                        w.WriteAttributeString("allowType", fieldUploadModel.allowType);
                        w.WriteAttributeString("defaultValue", fieldUploadModel.defaultValue);
                        break;
                }
                w.WriteEndElement();
            }
            #endregion
            w.WriteEndElement();

            w.WriteEndElement();

            w.WriteEndDocument();
            w.Flush();
            w.Close();
        }
    }
    #endregion


    #region 获取指定功能模块模板名称的功能模块对象
    /// <summary>
    /// 获取指定功能模块模板名称的功能模块对象
    /// </summary>
    /// <param name="fileFullName">功能模块模板名称（如：图片.xml）</param>
    /// <returns>功能模块对象</returns>
    public static Whir.Model.Whir_Model GetModleTemplateList(string fileFullName)
    {
        string filePath = HttpContext.Current.Server.MapPath("~/Temp/ModelTemplates/");
        XmlTextReader r = new XmlTextReader(filePath + fileFullName);

        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        while (r.Read())
        {
            if (r.NodeType == XmlNodeType.Element && r.Name == "ModelMark")
            {
                r.Read();
                model.moduleMark = r.Value;
                continue;
            }
            if (r.NodeType == XmlNodeType.Element && r.Name == "ModelName")
            {
                r.Read();
                model.modelName = r.Value;
                continue;
            }
            if (r.NodeType == XmlNodeType.Element && r.Name == "ModelDesc")
            {
                r.Read();
                model.modelDesc = r.Value;
                continue;
            }
            if (r.NodeType == XmlNodeType.Element && r.Name == "ModelIcon")
            {
                r.Read();
                model.modelIcon = r.Value;
                break;
            }
            if (r.NodeType == XmlNodeType.Element && r.Name == "TableName")
            {
                r.Read();
                model.tableName = r.Value;
                break;
            }
            if (r.NodeType == XmlNodeType.Element && r.Name == "IsUse")
            {
                r.Read();
                model.isUse = Convert.ToBoolean(r.Value);
                break;
            }
        }

        return model;
    }
    #endregion

    #region 导入功能模块
    /// <summary>
    /// 导入功能模块
    /// </summary>
    /// <param name="templateName">模板名称（如：图片.xml）</param>
    /// <param name="model">功能模块对象</param>
    /// <returns>返回导入状态</returns>
    public static bool Import(string templateName)
    {
        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        model = GetModleTemplateList(templateName);
        bool flag = false;
        flag = ModelTemplateHelper.Import(templateName, model.moduleMark, model.modelName, model.modelDesc, model.modelIcon, model.tableName, model.isUse);
        return flag;
    }
    #endregion

    /// <summary>
    /// 获取功能模块图片保存地址
    /// </summary>
    public static string GetModelIconPath()
    {
        return HttpContext.Current.Server.MapPath(Settings.GetString("ModelIconPath"));
    }

    /// <summary>
    /// 功能模块图片文件列表
    /// row["name"]：获取文件名
    /// </summary>
    /// <returns>功能模块图片文件列表</returns>
    public static DataTable GetModelIcons()
    {
        return FileSystemObject.GetDirectoryInfos(GetModelIconPath(), FsoMethod.File);
    }

    /// <summary>
    /// 获取功能模块模板保存地址
    /// </summary>
    public static string GetModelTemplatePath()
    {
        return HttpContext.Current.Server.MapPath(Settings.GetString("ModelTemplatePath"));
    }

    /// <summary>
    /// 功能模块模板导出文件列表
    /// row["name"]：获取文件名
    /// </summary>
    /// <returns>功能模块模板导出文件列表</returns>
    public static DataTable GetModelTemplates()
    {
        return FileSystemObject.GetDirectoryInfos(GetModelTemplatePath(), FsoMethod.File);
    }

    /// <summary>
    /// 生成实体类
    /// </summary>
    /// <param name="ModelID"></param>
    /// <returns></returns>
    public static bool CreateModelEntity(int ModelID,string path)
    {
        string tabSTR = "\t\t", enterSTR = "\r\n";
        bool btn = false;
        //try
        //{
            StringBuilder sbField = new StringBuilder();
            StringBuilder sbdeclare = new StringBuilder();
            StringBuilder sbdefine = new StringBuilder();
            StringBuilder sbundefine = new StringBuilder();

            DataTable dt = new Whir.BLL.Whir_Field().GetList("ModelID=" + ModelID).Tables[0];


            string str2 = "\t\t/// <summary>\r\n\t\t/// {3} \r\n\t\t/// </summary>\r\n\t\tpublic {1} {2}\r\n\t\t{\r\n\t\t\tset{ _{0} = value; }\r\n\t\t\tget{ return _{0}; }\r\n\t\t}\r\n\t\t\r\n";

            Whir.BLL.Whir_Model modelBll = new Whir.BLL.Whir_Model();
            Whir.Model.Whir_Model modelModel = new Whir.Model.Whir_Model();

            modelModel = modelBll.GetModel(ModelID);

            sbField.Append(tabSTR + "private int _" + modelModel.tableName.ToLower() + "_pid;\r\n");
            sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// 自增ID \r\n\t\t/// </summary>\r\n\t\tpublic int " + modelModel.tableName + "_PID" + "\r\n\t\t{\r\n\t\t\tset{ _" + modelModel.tableName.ToLower() + "_pid = value; }\r\n\t\t\tget{ return _" + modelModel.tableName.ToLower() + "_pid; }\r\n\t\t}\r\n\t\t\r\n");

            sbField.Append(tabSTR + "private bool _IsRecycle;\r\n");
            sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// 是否删除到回收站 \r\n\t\t/// </summary>\r\n\t\tpublic bool IsRecycle" + "\r\n\t\t{\r\n\t\t\tset{ _IsRecycle = value; }\r\n\t\t\tget{ return _IsRecycle; }\r\n\t\t}\r\n\t\t\r\n");

            foreach (DataRow dr in dt.Rows)
            {
                switch ((FieldType)int.Parse(dr["fieldType"].ToString()))
                {
                    case FieldType.MoneyType:                        
                        sbField.Append(tabSTR+"private float _" + dr["fieldName"].ToString().ToLower());
                        sbdeclare.Append(string.Format(str2, dr["fieldName"].ToString().ToLower(), "float", dr["fieldName"].ToString(), dr["alias"].ToString()));
                        break;
                    case FieldType.NumberType:
                        sbField.Append(tabSTR+"private int _" + dr["fieldName"].ToString().ToLower());
                        //sbdeclare.Append(string.Format(str2, dr["fieldName"].ToString().ToLower(), "int", dr["fieldName"].ToString(), dr["alias"].ToString()));
                        sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// " + dr["alias"].ToString() + " \r\n\t\t/// </summary>\r\n\t\tpublic int " + dr["fieldName"].ToString() + "\r\n\t\t{\r\n\t\t\tset{ _" + dr["fieldName"].ToString().ToLower() + " = value; }\r\n\t\t\tget{ return _" + dr["fieldName"].ToString().ToLower() + "; }\r\n\t\t}\r\n\t\t\r\n");
                        break;
                    case FieldType.DateTimeType:
                        sbField.Append(tabSTR+"private DateTime _" + dr["fieldName"].ToString().ToLower());
                        sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// " + dr["alias"].ToString() + " \r\n\t\t/// </summary>\r\n\t\tpublic DateTime " + dr["fieldName"].ToString() + "\r\n\t\t{\r\n\t\t\tset{ _" + dr["fieldName"].ToString().ToLower() + " = value; }\r\n\t\t\tget{ return _" + dr["fieldName"].ToString().ToLower() + "; }\r\n\t\t}\r\n\t\t\r\n");
                        break;
                    case FieldType.BoolType:
                        //sbField.Append(tabSTR+"private bool _" + dr["fieldName"].ToString().ToLower());
                        //sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// " + dr["alias"].ToString() + " \r\n\t\t/// </summary>\r\n\t\tpublic bool " + dr["fieldName"].ToString() + "\r\n\t\t{\r\n\t\t\tset{ _" + dr["fieldName"].ToString().ToLower() + " = value; }\r\n\t\t\tget{ return _" + dr["fieldName"].ToString().ToLower() + "; }\r\n\t\t}\r\n\t\t\r\n");
                        //break;
                    case FieldType.AreaType:
                    case FieldType.ListBoxType:
                    case FieldType.None:
                    case FieldType.TextType:
                    case FieldType.ColorType:
                    case FieldType.MultipleTextType:
                    case FieldType.LinkType:
                    case FieldType.MultipleHtmlTextType:
                    case FieldType.FileType:
                    case FieldType.PictureType:
                        sbField.Append(tabSTR+"private string _" + dr["fieldName"].ToString().ToLower());
                        sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// " + dr["alias"].ToString() + " \r\n\t\t/// </summary>\r\n\t\tpublic string " + dr["fieldName"].ToString() + "\r\n\t\t{\r\n\t\t\tset{ _" + dr["fieldName"].ToString().ToLower() + " = value; }\r\n\t\t\tget{ return _" + dr["fieldName"].ToString().ToLower() + "; }\r\n\t\t}\r\n\t\t\r\n");
                        break;
                    default:                            
                        sbField.Append(tabSTR + "private string _" + dr["fieldName"].ToString().ToLower());
                        sbdeclare.Append("\t\t/// <summary>\r\n\t\t/// " + dr["alias"].ToString() + " \r\n\t\t/// </summary>\r\n\t\tpublic string " + dr["fieldName"].ToString() + "\r\n\t\t{\r\n\t\t\tset{ _" + dr["fieldName"].ToString().ToLower() + " = value; }\r\n\t\t\tget{ return _" + dr["fieldName"].ToString().ToLower() + "; }\r\n\t\t}\r\n\t\t\r\n");
                        break;
                }
                sbdefine.Append("//" + modelModel.tableName.ToLower() + "." + dr["fieldName"].ToString() + " = " + dr["fieldName"].ToString() + ".FieldValue;\r\n\t\t");
                sbundefine.Append("//" + dr["fieldName"].ToString() + ".FieldValue" + " = " + modelModel.tableName.ToLower() + "." + dr["fieldName"].ToString() +";\r\n\t\t");
                sbField.Append(";\r\n");
            }

            StringBuilder sb = new StringBuilder();

            //读文件
            string str = "";
            using (StreamReader sr = new StreamReader(path + "templete.tmp", Encoding.UTF8))
            {
                str = sr.ReadToEnd();
            }            

            str = str.Replace("{$ModelDesc}", modelModel.modelName);
            str = str.Replace("{$ModelName}", modelModel.tableName);

            str = str.Replace("{$Fields}", sbField.ToString() + enterSTR + sbdeclare.ToString());

            str = str.Replace("{$other}", sbdefine.ToString());
            str = str.Replace("{$other2}", sbundefine.ToString());

            WriteFile(path + modelModel.tableName+".cs", str);

            btn = true;
        //}
        //catch(SystemException ErrorEventArgs){
        //    string msg = ErrorEventArgs.Message;
        //}

        return btn;
    }


    /// <summary>
    /// 把文件内容写入目标文件
    /// </summary>
    /// <param name="filepath"></param>
    /// <param name="filecontent"></param>
    public static void WriteFile(string filepath, string filecontent)
    {
        FileInfo file = new FileInfo(filepath);
        if (!Directory.Exists(file.DirectoryName))
        {
            Directory.CreateDirectory(file.DirectoryName);
        }

        using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
            {
                sw.Write(filecontent);
            }
        }
    }
}
